package cn.jiaqiang.chatgpt.data.infrastructure.repository;

import cn.jiaqiang.chatgpt.data.domain.openai.repository.IUserAccountRepository;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.UserAccountStatusVO;
import cn.jiaqiang.chatgpt.data.domain.snow.SnowflakeIdGenerator;
import cn.jiaqiang.chatgpt.data.infrastructure.dao.IUserAccountDao;
import cn.jiaqiang.chatgpt.data.infrastructure.po.UserAccountPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * User: jia-qiang
 * Date: 2024-04-09
 * Time: 16:08
 */
@Slf4j
@Repository
public class UserAccountRepository implements IUserAccountRepository {

    @Resource
    protected ThreadPoolExecutor threadPoolExecutor;

    @Resource
    protected SnowflakeIdGenerator snowflakeIdGenerator;

    @Resource
    private IUserAccountDao userAccountDao;

    /**
     * 新用户开户
     */
    @Override
    public String insertUserAccount(UserAccountEntity userAccountEntity) {

        UserAccountPO userAccount = userAccountDao.queryUserAccount(userAccountEntity.getOpenid());
        if (userAccount != null) {
            // 已经存在,不需要再进行开户了, 返回 null, 不能用发送401, 而应该是发送用户ID
            return userAccount.getUserId().toString();
        }
        Long userId = snowflakeIdGenerator.nextId();
        UserAccountPO userAccountPO = new UserAccountPO();
        userAccountPO.setTotalQuota(0);
        userAccountPO.setSurplusQuota(0);
        userAccountPO.setOpenid(userAccountEntity.getOpenid());
        userAccountPO.setUserId(userId);

        return userAccountDao.insertUserAccount(userAccountPO) == 1 ? userId.toString() : "";
    }
    /**
     * 通过用户id, openid查询用户
     */
    @Override
    public UserAccountEntity queryUserByUserId(String userId) {
        UserAccountPO userAccountPO = userAccountDao.queryUserByUserId(userId);
        if (userAccountPO == null) {
            return null;
        }
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        userAccountEntity.setOpenid(userAccountPO.getOpenid());
        userAccountEntity.setUserId(userAccountPO.getUserId());
        userAccountEntity.setTotalQuota(userAccountPO.getTotalQuota());
        userAccountEntity.setSurplusQuota(userAccountPO.getSurplusQuota());
        userAccountEntity.setUserAccountStatusVO(UserAccountStatusVO.getInfo(userAccountPO.getStatus()));

        return userAccountEntity;
    }

    @Override
    public void updateUserOpenIdWithUserId(String openId, String userId) {
        threadPoolExecutor.execute(() -> {
            // 1. 删除"无用的账号"
            userAccountDao.deleteDeprecatedUserAccount(openId);
            // 2. 迁移账号
            userAccountDao.updateUserOpenIdWithUserId(openId, userId);
        });
    }
}
